package com.sdy.supermarket.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.MapUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.supermarket.biz.model.*;
import com.sdy.supermarket.biz.service.*;
import com.sdy.common.model.Response;
import com.sdy.supermarket.biz.vo.CoopVO;
import com.sdy.supermarket.biz.vo.ResIntroVO;
import com.sdy.supermarket.biz.vo.ResSimpleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sdy.mvc.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源表 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2019-07-31
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/gsRes")
public class GsResController extends BaseController {
    @Autowired
    private GsResService gsResService;
    @Autowired
    private GsResDocService gsResDocService;
    @Autowired
    private GsResFeatrueService gsResFeatrueService;
    @Autowired
    private GsBannerManageService gsBannerManageService;
    @Autowired
    private GsCategoryManageService gsCategoryManageService;
    @Autowired
    private GsCooperationUnitService gsCooperationUnitService;
    @Autowired
    private FsApi fsApi;
    @Autowired
    private GsHotResService gsHotResService;

    @GetMapping("/indexMap")
    public Response indexMap() {
        Map<String, Object> indexMap = new HashMap<>();
        // 热门产品
        List<GsHotRes> hostResList = gsHotResService.list(Wrappers.<GsHotRes>lambdaQuery().orderByAsc(GsHotRes::getSort).eq(GsHotRes::getDisplayStatus, 0)
                .last("limit 0, 8"));
        List<FileObj> hotResfileList = fsApi.getFileListInfo(hostResList.stream().map(GsHotRes::getImgUrl).collect(Collectors.toList()));
        for (FileObj s : hotResfileList) {
            for (GsHotRes hotRes : hostResList) {
                if (hotRes.getImgUrl().equals(s.getId())) {
                    hotRes.setFileInfo(s);
                }
            }
        }
        indexMap.put("hostResList", hostResList);
        // 产品特色
        List<GsResFeatrue> resFeatureList = gsResFeatrueService.listValidResFeature();
        List<FileObj> fileListInfo = fsApi.getFileListInfo(resFeatureList.stream().map(GsResFeatrue::getFeatureImgUrl).collect(Collectors.toList()));
        for (FileObj ffile : fileListInfo) {
            for (GsResFeatrue resfeat : resFeatureList) {
                if (resfeat.getFeatureImgUrl().equals(ffile.getId())) {
                    resfeat.setFileInfo(ffile);
                }
            }
        }
        indexMap.put("resFeatureList", resFeatureList);
        // banner
        List<GsBannerManage> bannerList = gsBannerManageService.listValidBanner();
        if (null != bannerList.get(0).getBannerImgUrl()) {
            bannerList.get(0).setFileInfo(fsApi.getFileInfo(bannerList.get(0).getBannerImgUrl()));
        }
        indexMap.put("bannerList", bannerList);
        // 合作单位
        List<CoopVO> coopList = gsCooperationUnitService.listValidCoop();
        indexMap.put("coopList", coopList);
        return Response.success(indexMap);
    }

    /**
     * 根据资源id查询资源，不传则默认查询所有
     *
     * @param id 资源id
     * @return Response
     */
    @GetMapping("/getResById")
    public Response get(Integer id) throws BizException {
        GsRes res = gsResService.getById(id);
        Assert.isNull(res, "资源不存在！");
        List<GsResDoc> docList = gsResDocService.list(
                new LambdaQueryWrapper<GsResDoc>().eq(GsResDoc::getResId, res.getId())
        );
        res.setDocList(docList);
        res.setResIntroVO(JsonUtil.fromJson(res.getIntroduction(), ResIntroVO.class));
        res.setIntroduction(null);
        return Response.success(res);
    }

    /**
     * 分类资源
     *
     * @param category 分类 1-云基础产品 2-数据产品 3-最多跑一次
     * @param type     类型 0-普通资源 1-服务类资源
     */
    @GetMapping("/listDataMap")
    public Response listDataMap(Integer category, Integer type) {
        List<GsRes> resList = gsResService.listRes(category, type);
        List<FileObj> listInfo = fsApi.getFileListInfo(resList.stream().map(GsRes::getIcon).collect(Collectors.toList()));
        for (GsRes res : resList) {
            for (FileObj file : listInfo) {
                if (res.getIcon().equals(file.getId())) {
                    res.setIconInfo(file);
                }
            }
        }
        List<ResSimpleVO> resSimpleVOList = resList.stream().map(ResSimpleVO::format).collect(Collectors.toList());
        Map<Integer, List<ResSimpleVO>> resultMap = new HashMap<>();
        Map<String, List<ResSimpleVO>> resultMap2 = new HashMap<>();
        resSimpleVOList.stream().filter(item -> item.getCategory() != null).forEach(item -> {
            resultMap.computeIfAbsent(item.getCategory(), k -> new ArrayList<>());
            resultMap.get(item.getCategory()).add(item);
        });
        // 查询分类名
        if (!resultMap.isEmpty()) {
            List<GsCategoryManage> categorys = gsCategoryManageService.list(new LambdaQueryWrapper<GsCategoryManage>()
                    .in(GsCategoryManage::getId, resultMap.keySet()));
            Map<Integer, GsCategoryManage> categoryManageMap = MapUtil.collectionToMap(categorys, GsCategoryManage::getId);
            resultMap.forEach((k, v) -> {
                GsCategoryManage categoryManage = categoryManageMap.get(k);
                resultMap2.put(categoryManage == null ? k.toString() : categoryManage.getCategoryName(), v);
            });
        }
        return Response.success(resultMap2);
    }

    /**
     * 所有资源
     *
     * @param category 分类 1-云基础产品 2-数据产品 3-最多跑一次
     * @param type     类型 0-普通资源 1-服务类资源
     */
    @GetMapping("/listData")
    public Response listData(HttpServletRequest request, Integer category, Integer type) {
        List<GsRes> result = gsResService.listRes(category, type);
        return Response.success(result);
    }

    /**
     * 查询所有上架的资源
     *
     * @return
     */
    @GetMapping("/getResList")
    public Response getResList() {
        List<GsRes> list = gsResService.list(Wrappers.<GsRes>lambdaQuery().eq(GsRes::getState, 1).orderByDesc(GsRes::getCreateTime));
        return Response.success(list);
    }

    /**
     * 获取单条数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getOne")
    public Response getOne(Integer id) throws BizException {
        GsRes byId = gsResService.getById(id);
        Assert.isNull(byId, "资源不存在");
        return Response.success(byId);
    }


//    /**
//     * 用户资源
//     */
//    @GetMapping("/myResList")
//    public Response myResList(HttpServletRequest request) {
//        LambdaQueryWrapper<GsRes> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(category != null, GsRes::getCategory, category)
//                .eq(type != null, GsRes::getType, type)
//                .eq(GsRes::getState, 0)
//                .orderByDesc(GsRes::getId);
//        List<GsRes> result = gsResService.list(wrapper);
//        return Response.success(result);
//    }
}
